/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;
using System.Text;

using TypeElement = argot.TypeElement;
using TypeException = argot.TypeException;
using TypeInputStream = argot.TypeInputStream;
using TypeOutputStream = argot.TypeOutputStream;
using TypeReader = argot.TypeReader;
using TypeWriter = argot.TypeWriter;

namespace argot.common
{
	
	/// <summary> 
	/// This is a string encoded in UTF8 format. 
	/// It uses a single unsigned u32 to specify the length.
	/// </summary>
	public class U32UTF8 
	:TypeReader, TypeWriter
	{
		
		public const System.String TYPENAME = "u32utf8";
		
		public virtual System.Object Read(TypeInputStream inStream, TypeElement element)
		{
			System.Int64 id = (System.Int64) inStream.ReadObject(BigEndianUnsignedInteger.TYPENAME);
			
			if ((int) id > 0)
			{
				
				byte[] bytes = new byte[(int) id];
				
				int read = inStream.Stream.Read(bytes,0,(int)id);
				if (read < (int) id)
					System.Console.Out.WriteLine("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%BAD");
				
				System.String ret = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);
				
				return ret;
			}
			
			return new System.Text.StringBuilder("").ToString();
		}
		

		public virtual void Write(TypeOutputStream outStream, System.Object o, TypeElement element)
		{
			if (!(o is System.String))
			{
				if (o == null)
				{
					outStream.WriteObject(BigEndianUnsignedInteger.TYPENAME, (System.Object) 0);
					return ;
				}
				throw new TypeException("StringType: can only write objects of type String");
			}
			
			System.String s = (System.String) o;
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			int len = bytes.Length;
			
			outStream.WriteObject(BigEndianUnsignedInteger.TYPENAME, (System.Object) len);
			outStream.Stream.Write(bytes, 0, len);
		}
	}
}